package mytask.domain;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.servlet.http.HttpSession;

import mytask.model.User;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class AuthManager {

	public static HttpSession session() {
		ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
		return attr.getRequest().getSession(true);
	}

	public static void setPageUser(User user) {
		session().setAttribute("AUTH_DATA", user);
	}

	public static User getPageUser() {
		return ((User) session().getAttribute("AUTH_DATA"));
	}

	public static boolean isUserLoggedIn() {
		return getPageUser() != null;
	}

	public static String getSHA1(String password) {
		try {
			MessageDigest md = MessageDigest.getInstance("SHA1");
			byte[] messageDigest = md.digest(password.getBytes());
			BigInteger number = new BigInteger(1, messageDigest);
			return number.toString(16);
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
	}
}
